package com.linkage.jz.bankruptcy.fragment.Project;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProFlowActivity;
import com.linkage.jz.bankruptcy.activity.Project.CreateProjectDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProFlowDetailActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProNodeInfo;
import com.linkage.jz.bankruptcy.bean.ProNodeInfoAuth;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.LogUtil;
import com.linkage.jz.bankruptcy.utils.MapUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.app.Activity.RESULT_OK;

/**
 * @author AFAP
 * Fragment-节点
 */
public class ProFlowFragment extends Fragment {

    public static final String MERCHANT_DETAILS_PAGE = "MERCHANT_DETAILS_PAGE";
    private static String ARG_PARAM_ACTION = "ARG_PARAM_ACTION";
    private static String ARG_PARAM_PROJECTID = "ARG_PARAM_PROJECTID";

    public static String KEY_FLOW_NAME = "KEY_FLOW_NAME";
    public static String KEY_FLOW_ID = "KEY_FLOW_ID";

    public static String ACTION_SELECT = "ACTION_SELECT";


    private String mProjectId;
    private String mAction;

    private RecyclerView mRecyclerView;
    private FlowAdapter mAdapter;
    private List<ProNodeInfo> mData;
    private Boolean mEditflag;
    private ProNodeInfoAuth auth;
    private TextView flow_edit;


    public static ProFlowFragment newInstance(int page, String proID) {
        Bundle args = new Bundle();
        args.putInt(MERCHANT_DETAILS_PAGE, page);
        args.putString(ARG_PARAM_PROJECTID, proID);
        ProFlowFragment tripFragment = new ProFlowFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }

    public static ProFlowFragment newInstance(int page, String proID, String action) {
        Bundle args = new Bundle();
        args.putInt(MERCHANT_DETAILS_PAGE, page);
        args.putString(ARG_PARAM_PROJECTID, proID);
        args.putString(ARG_PARAM_ACTION, action);
        ProFlowFragment tripFragment = new ProFlowFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mProjectId = getArguments().getString(ARG_PARAM_PROJECTID);
        mAction = getArguments().getString(ARG_PARAM_ACTION);
    }

    private Timer mTimer;

    @Override
    public void onResume() {
        super.onResume();
        try {
//            ProDetailActivity parentActivity = (ProDetailActivity) getActivity();
//            parentActivity.showLoading();
            if(mEditflag)
            {
                getList();
            }else {
                getListZQ();
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        LogUtil.i("ProFlowFragment", "-------->开启定时器");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.notifyDataSetChanged();
                    }
                });
            }
        };
        mTimer = new Timer();
        mTimer.schedule(task, 1000, 1000);
    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtil.i("ProFlowFragment", "-------->关闭定时器");
        mTimer.cancel();
        mTimer = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_FLOW)) {
            if(mEditflag)
            {
                getList();
            }else {
                getListZQ();

            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_detailpro_flow, container, false);
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        mData = new ArrayList<>();
        initAdapter(mData);
        mEditflag = false;
        flow_edit = view.findViewById(R.id.flow_edit);
        flow_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                finish();
                mEditflag = !mEditflag;
//                mAdapter.notifyDataSetChanged();
                if(mEditflag)
                {
                    flow_edit.setText("关闭编辑");
                    getList();
                }else {
                    flow_edit.setText("开启编辑");
                    getListZQ();

                }
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        refreshAction();
        if(mEditflag)
        {
            getList();
        }else {
            getListZQ();

        }
    }

    private void refreshAction() {
        View ll_pro_module_item_add = getView().findViewById(R.id.ll_pro_module_item_add);
        View area_pro_module_nodata_tip = getView().findViewById(R.id.area_pro_module_nodata_tip);
        TextView tv_pro_module_item_add0 = getView().findViewById(R.id.tv_pro_module_item_add0);
        TextView tv_pro_module_item_add = getView().findViewById(R.id.tv_pro_module_item_add);
        TextView tv_pro_module_nodata_tip = getView().findViewById(R.id.tv_pro_module_nodata_tip);



        tv_pro_module_nodata_tip.setText("还没有进度记录");
        tv_pro_module_item_add.setText("添加节点");
        tv_pro_module_item_add0.setText("添加节点");

        if (mData.size() > 0) {
            ll_pro_module_item_add.setVisibility(View.GONE);
            area_pro_module_nodata_tip.setVisibility(View.GONE);
        } else {
            ll_pro_module_item_add.setVisibility(View.GONE);
            area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
            tv_pro_module_item_add.setVisibility(View.GONE);
        }
    }

    /**
     * 设置RecyclerView属性
     */
    private void initAdapter(List<ProNodeInfo> data) {
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration
// .VERTICAL_LIST));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new FlowAdapter(getActivity(), R.layout.fragment_pro_detailpro_flow_item, data);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);//设置adapter


        //设置item点击事件
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                switch (view.getId()) {
                    case R.id.rl_flow_add:
                        if (mEditflag) {
                            Intent intent = new Intent(getActivity(), CreateProFlowActivity.class);
                            intent.putExtra(BaseActivity.KEY_PROJECTID, mProjectId);
                            intent.putExtra(CreateProFlowActivity.KEY_CODE, mData.get(position).getModelCode());
                            startActivity(intent);
                        }
                        break;
                    case R.id.flow_edit:
                        mEditflag = !mEditflag;
                        mAdapter.notifyDataSetChanged();
                        break;
                    case R.id.ll_flow_item:
                        // 用于节点选择的场景
                        if (TextUtils.equals(mAction, ACTION_SELECT)) {
                            Intent intent = new Intent();
                            intent.putExtra(KEY_FLOW_NAME, mData.get(position).getNodeName());
                            intent.putExtra(KEY_FLOW_ID, mData.get(position).getId());
                            getActivity().setResult(RESULT_OK, intent);
                            getActivity().finish();
                            return;
                        }
                        if (mEditflag) {
                            ProNodeInfo info  = mData.get(position);
                            if(info.isStaging()) {
                                Intent intent = new Intent(getActivity(), CreateProFlowActivity.class);
                                intent.putExtra(CreateProFlowActivity.KEY_ACTION, "edit");
                                intent.putExtra(CreateProFlowActivity.KEY_FLOW, info);
                                startActivity(intent);
                            }else{
                                Intent intent = new Intent(getActivity(), ProFlowDetailActivity.class);
                                intent.putExtra(BaseActivity.KEY_PROJECTID, mProjectId);
                                intent.putExtra(ProFlowDetailActivity.KEY_ID, mData.get(position).getId());
                                intent.putExtra(CreateProFlowActivity.KEY_FLOW, mData.get(position));
                                startActivity(intent);
                            }
                        } else {
                            Intent intent = new Intent(getActivity(), ProFlowDetailActivity.class);
                            intent.putExtra(BaseActivity.KEY_PROJECTID, mProjectId);
                            intent.putExtra(ProFlowDetailActivity.KEY_ID, mData.get(position).getId());
                            intent.putExtra(CreateProFlowActivity.KEY_FLOW, mData.get(position));
                            startActivity(intent);
                        }
                        break;
                    case R.id.tv_address:
                        final List<String> values = new ArrayList<String>();

                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

                        //builder.setIcon(R.drawable.ic_launcher);
                        builder.setTitle("请选择");
                        //    指定下拉列表的显示数据
                         String[] strTypes = new String[]{};
                         int num = 0;
                        if(MapUtil.isBaiduMapInstalled())
                        {
                            strTypes = Arrays.copyOf(strTypes, num+1);

                            strTypes[num]="百度地图";
                            num++;
                        }
                        if(MapUtil.isGdMapInstalled())
                        {
                            strTypes = Arrays.copyOf(strTypes, num+1);

                            strTypes[num]="高德地图";
                            num++;
                        }
                        if(MapUtil.isTencentMapInstalled())
                        {
                            strTypes = Arrays.copyOf(strTypes, num+1);

                            strTypes[num]="腾讯地图";
                            num++;
                        }
                        final String[] finalstrTypesp= strTypes;

                        final String addr = mData.get(position).getSysAddressInfo().getFullAddress();
                        //    设置一个下拉的列表选择项
                        builder.setItems(finalstrTypesp, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                    if("百度地图".equalsIgnoreCase(finalstrTypesp[which]))
                                    {
                                        MapUtil.openBaiDuNavi(getActivity(), 0, 0, addr);
                                    }else if("高德地图".equalsIgnoreCase(finalstrTypesp[which]))
                                    {
                                        MapUtil.openGaoDeNavi(getActivity(), 0, 0, addr);
                                    }else{
                                        MapUtil.openTencentMap(getActivity(), 0, 0, addr);
                                    }

                            }
                        });
                        builder.show();
                        break;
                }
            }
        });

    }

    class FlowAdapter extends BaseQuickAdapter<ProNodeInfo, BaseViewHolder> {
        int mLayoutId;

        public FlowAdapter(Context context, int LayoutId, List<ProNodeInfo> str) {
//
            super(LayoutId, str);
//            Log.e("=========----====FlowAdapter",LayoutId+"");
//            mLayoutId = R.layout.fragment_pro_detailpro_flow_item;
        }

        @Override
        public void convert(BaseViewHolder helper, ProNodeInfo info) {
            int position = helper.getAdapterPosition();

            helper.addOnClickListener(R.id.rl_flow_add);
//            helper.addOnClickListener(R.id.flow_edit);
            helper.addOnClickListener(R.id.ll_flow_item);
            helper.addOnClickListener(R.id.tv_address);


            if (auth != null && auth.getAddSchedule()) {
//                if (position == 0) {
//                    helper.setVisible(R.id.flow_edit, true);
//                } else {
//                    helper.setVisible(R.id.flow_edit, false);
//                }

                helper.setText(R.id.flow_title, info.getNodeName()+"   ");
                TextView flow_title = helper.getView(R.id.flow_title);
                if (mEditflag) {

                    helper.setVisible(R.id.flow_add, true);
//                    helper.setText(R.id.flow_edit, "关闭编辑");
                    if (auth != null && auth.getEditSchedule()) {
//                        helper.setVisible(R.id.flow_title_edit, true);
                        if (info.isStaging()) {
                            //显示

                            SpannableString ss = new SpannableString(info.getNodeName()+"   ");
                            int len = ss.length();
                            //图片
                            Drawable d = ContextCompat.getDrawable(mContext, (R.drawable.ic_pro_flow_edit));
                            d.setBounds(10, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                            //构建ImageSpan
                            ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
                            ss.setSpan(span, len-1 , len, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                            flow_title.setText(ss);

//                            helper.setGone(R.id.flow_title_edit, true);
                        } else {
                            //隐藏
                            helper.setVisible(R.id.flow_title_edit, false);
                        }
                    } else {
                        //隐藏
                        helper.setVisible(R.id.flow_title_edit, false);
                    }
                } else {
//                    helper.setText(R.id.flow_edit, "开启编辑");
                    helper.setVisible(R.id.flow_add, false);
                    //隐藏
                    helper.setVisible(R.id.flow_title_edit, false);
                }
            } else {
//                helper.setVisible(R.id.flow_edit, false);
                helper.setVisible(R.id.flow_add, false);
            }


            String opText;
            if (info.isStaging()) {
                opText = "未设置";
            } else {
                opText = DateFormatUtils.long2Str(info.getStartTime(), false);
            }
            helper.setText(R.id.flow_time_opt, opText);

//            if (info.isStaging()) {
//                helper.setGone(R.id.flow_title_edit, true);
//            } else {

//            }


            if (info.getTimeType() == null) {
                helper.setGone(R.id.tv_time_start, false);
                helper.setGone(R.id.tv_time_end, false);
                helper.setGone(R.id.tv_time, false);
            } else if (TextUtils.equals(info.getTimeType().getValue(), "0")) {

                helper.setGone(R.id.tv_time_start, false);
                helper.setGone(R.id.tv_time_end, false);

                if (info.getStartTime() > 0) {
                    helper.setGone(R.id.tv_time, true);
                    helper.setText(R.id.tv_time, "时间：" + DateFormatUtils.long2Str(info.getStartTime(), true));
                } else {
                    helper.setGone(R.id.tv_time, false);
                }

            } else {
                helper.setGone(R.id.tv_time, false);
                helper.setGone(R.id.tv_time_start, true);
                helper.setGone(R.id.tv_time_end, true);
                helper.setText(R.id.tv_time_start, "开始时间：" + DateFormatUtils.long2Str(info.getStartTime(), true));
                if(info.getEndTime() !=0l) {
                    helper.setText(R.id.tv_time_end, "结束时间：" + DateFormatUtils.long2Str(info.getEndTime(), true));
                }else{
                    helper.setText(R.id.tv_time_end, "结束时间：待定" );
                }
            }

            // 倒计时条件较多，先隐藏，再根据情况显示
            helper.setGone(R.id.area_countdown, false);
            if (info.isCountdown() && !info.isStaging()) {
                long gap = 0;
                if (info.getTimeType() == null) {

                } else if (TextUtils.equals(info.getTimeType().getValue(), "0")) {
                    gap = info.getStartTime() - (System.currentTimeMillis() / 1000);
                } else {
                    if (System.currentTimeMillis() > info.getStartTime() * 1000) {
                        gap = info.getEndTime() - (System.currentTimeMillis() / 1000);
                    }
                }
                if (gap > 0) {
                    helper.setGone(R.id.area_countdown, true);
                    helper.setText(R.id.tv_countdown, formatTimeGap(gap));
                }
            }

            if (info.getSysAddressInfo() != null) {
                helper.setGone(R.id.tv_address, true);
                helper.setText(R.id.tv_address, "地址：" + info.getSysAddressInfo().getFullAddress());

            } else {
                helper.setGone(R.id.tv_address, false);
            }
        }
    }

    public static String formatTimeGap(long gap) {
        if (gap < 0) {
            return "已结束";
        }
        long day = 0;
        long hour = 0;
        long min = 0;
        long second = 0;
        if (gap < 60) {
            second = gap;
        } else if (gap < 3600) {
            min = (long) Math.ceil(gap / 60);
            second = gap - 60 * min;
        } else if (gap < 86400) {
            hour = (long) Math.ceil(gap / 3600);
            gap = gap - 3600 * hour;
            min = (long) Math.ceil(gap / 60);
            second = gap - 60 * min;
        } else {
            day = (long) Math.ceil(gap / 86400);
            gap = gap - 86400 * day;
            hour = (long) Math.ceil(gap / 3600);
            gap = gap - 3600 * hour;
            min = (long) Math.ceil(gap / 60);
            second = gap - 60 * min;
        }


        return day + "天" + hour + "时" + min + "分" + second + "秒";
    }

    public void getList() {

        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .getFlowList_Manager(userToken, mProjectId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        JsonArray arr = data.getAsJsonArray("projectScheduleList");
                        List<ProNodeInfo> list = ProNodeInfo.parse(arr);

                        auth = new Gson().fromJson(data.getAsJsonObject("auth"), ProNodeInfoAuth.class);

                        mData.clear();
                        mAdapter.notifyDataSetChanged();

                        mData.addAll(list);
                        mAdapter.notifyDataSetChanged();
                        refreshAction();
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

    public void getListZQ() {

        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");
        Network
                .getAPIService()
                .getNodeCrList(userToken, mProjectId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        JsonArray arr = data.getAsJsonArray("projectScheduleList");
                        List<ProNodeInfo> list = ProNodeInfo.parse(arr);

                        auth = new Gson().fromJson(data.getAsJsonObject("auth"), ProNodeInfoAuth.class);

                        if (auth != null && auth.getAddSchedule()) {
                            flow_edit.setVisibility(View.VISIBLE);



                        } else {
                            flow_edit.setVisibility(View.GONE);
                        }
                        mData.clear();
                        mAdapter.notifyDataSetChanged();

                        mData.addAll(list);
                        mAdapter.notifyDataSetChanged();
                        refreshAction();
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

}
